package yxy.game.pm2.command.arena;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.arenaweekreward;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ArenaMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.arena.ArenaPlayerModule;

/** 竞技场 领取宝箱奖励 */
@MessageType(proto = Command.ArenaTreasureChest, classtype = ArenaMessage.ArenaTreasureChestRequest.class)
public class CMD_ArenaTreasureChest extends Command<ArenaMessage.ArenaTreasureChestRequest> {

	@Override
	public void execute(MessageSource messageSource, ArenaMessage.ArenaTreasureChestRequest request) {
		String playerCode = messageSource.getTag();
		int weekbox = request.getWeekbox();

		ArenaMessage.ArenaTreasureChestResponse.Builder response = ArenaMessage.ArenaTreasureChestResponse.newBuilder();

		ArenaPlayerModule module = ArenaPlayerModule.get(playerCode);
		if (module == null) {
			send(messageSource, response, Result.ModuleNotOpen);// 竞技场模块没有开启
			return;
		}

		try {
			if (module.tryLock()) {

				String weekboxCode = String.valueOf(weekbox);
				if (module.getWeekbox().contains(weekboxCode)) {
					send(messageSource, response, Result.ArenaBoxRewarded);// 宝箱已领过
					return;
				}
				arenaweekreward data = DataCenter.getData(weekbox, arenaweekreward.class);
				if (data == null) {
					send(messageSource, response, Result.ParamError);
					return;
				}
				if (module.getWeektimes() < data.getCondition()) {
					// 条件不足以领取
					send(messageSource, response, Result.ArenaTimesLack);// 挑战次数不足
					return;
				}
				Currency reward = Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum());
				new CurrencyHandle().addCurrency(playerCode, CCReason.竞技场, reward);
				module.getWeekbox().add(weekboxCode);
				module.set();

				response.addRewards(new CurrencyHandle().packItem(reward));

				send(messageSource, response, Result.Success);

			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			module.unlock();
		}
	}

	private void send(MessageSource messageSource, ArenaMessage.ArenaTreasureChestResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}